% This code predicts optimal 2nd-period price conditional on firm j and
% state k.
function [p2_new_jk, exitflag] = predict_p2(cost2_0_jk, cost2_1_jk, p_j1, p_jk2_ini, claims_jk, ...
    Delta_xi_jj, s1_ind1_jj,...
    resource_y2, B2_c, alpha, rho, crra, pr_y, U_lapse, cost_weight, use_cost_weight, options)
%% solve for optimal price increase
% use the FOC w.r.t. p_jk2
ff=@(x0)foc_2nd(x0, cost2_1_jk, p_j1, claims_jk, s1_ind1_jj, ...
    resource_y2, B2_c, alpha, rho, crra, Delta_xi_jj, pr_y, U_lapse, cost_weight, use_cost_weight);

[p_jk2_star, fval, exitflag] = fsolve(ff, p_jk2_ini, options);

if p_jk2_star<p_j1
    p_jk2_star=p_j1;
end
%% 2nd-period profit conditional on price increase
% 2nd-period mkt share
[s_jk2_star, stay_vec_star] = predict_s_jk2(p_jk2_star, s1_ind1_jj, Delta_xi_jj, U_lapse,...
    resource_y2, pr_y, B2_c, alpha, rho, crra);

% claims x mkt share
N_y = length(pr_y);
claims_av_jk_star = sum(cost_weight.*repmat(claims_jk, N_y, 1).*s1_ind1_jj.*stay_vec_star.*pr_y);

% rate adjustment cost
cost_rs_star = cost2_0_jk + 0.5*cost2_1_jk*(p_jk2_star-p_j1);

% 2nd-period profit
if use_cost_weight==0
    profit_star = (p_jk2_star-claims_jk)*s_jk2_star - cost_rs_star;
else
    profit_star = p_jk2_star*s_jk2_star - claims_av_jk_star - cost_rs_star;
end

%% 2nd-period profit conditional on no price increase
% 2nd-period mkt share
p_jk2_n = p_j1;
[s_jk2_n, stay_vec_n] = predict_s_jk2(p_jk2_n, s1_ind1_jj, Delta_xi_jj, U_lapse,...
    resource_y2, pr_y, B2_c, alpha, rho, crra);

% claims x mkt share
claims_av_jk_n = sum(cost_weight.*repmat(claims_jk, N_y, 1).*s1_ind1_jj.*stay_vec_n.*pr_y);

% 2nd-period profit
if use_cost_weight==0
    profit_n = (p_jk2_n-claims_jk)*s_jk2_n;
else
    profit_n = p_jk2_n*s_jk2_n - claims_av_jk_n;
end

%% store optimal 2nd-period price
if profit_star>profit_n
    p2_new_jk = p_jk2_star;
else
    p2_new_jk = p_j1;
end